//
//  JQFXHLoanSubmitmmViewController.swift
//  jiuzhoudai
//
//  Created by 卢小艳 on 2025/7/9.
//

import Foundation
import UIKit
import CleanJSON


class JQFXHLoanSubmitmmViewController: HJYJBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var jqfxhLastnnPara : [String: String] = [:]
    var jqfxhListoos: [JQFXHLoanListuuItemModel] = []

    
    var jqfxhParappDic : [String: String] = [:]
    
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(para: [String: String]) {
        self.jqfxhLastnnPara = para
        super.init(nibName: nil, bundle: nil)
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.view.endEditing(true)
    }
    
     override func viewDidLoad() {
        super.viewDidLoad()
        
         title = "申请额度"
        
         self.view.backgroundColor = UIColor.jqfxhSmallViewBgbbGray
         
         var json = "jqfxhLoansslist"
         
         if JQFXHNetworkManager.shared.partnerId == 3 {
             json = "jqfxhShengrddLoanlist"
         }
         
         guard let url = Bundle.main.url(forResource: json, withExtension: "json"),
               let data = try? Data(contentsOf: url) else {
             return
         }
         do {
             let jqfxhListqqData = try CleanJSONDecoder().decode(JQFXHLoanvvListModel.self, from: data)
             self.jqfxhListoos = jqfxhListqqData.array
         } catch {
         }
         jqfxhSetrrupUI()
         
         NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        // 获取键盘高度
        if let userInfo = notification.userInfo,
           let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
            let keyboardHeight = keyboardFrame.height
            self.jqfxhCollectionvvView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
        }
    }

    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardWillHide(_ notification: Notification) {
        self.jqfxhCollectionvvView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

    }
    
    
    
    @objc func jqfxhUploadttLoan() {
        JQFXHHUD.jqfxhShowssLoading()
        let merged = jqfxhParappDic.merging(jqfxhLastnnPara) { (_, new) in new }
        if JQFXHNetworkManager.shared.partnerId == 3 {
            let provider = JQFXHNetworkManager.shared.shengrProvider
            JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhLoanmApply(dic: merged)) { result in
                JQFXHHUD.jqfxhHttidden()
                switch result {
                case.success(_):
                    self.jqfxhCheckqqInfo()
                case .failure(let error):
                    print(error)
                }
            }
        }else {
            let provider = JQFXHNetworkManager.shared.provider
            JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhLoanmApply(dic: merged)) { result in
                JQFXHHUD.jqfxhHttidden()
                switch result {
                case.success(let json):
                    print(json)
                    self.jqfxhToSuccessrrVC()
                case .failure(let error):
                    print(error)
                }
            }
        }
                
    }
    
    
    func jqfxhCheckqqInfo() -> Void {
        let provider = JQFXHNetworkManager.shared.shengrProvider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhCheckzzinto, type: JQFXHSrCheckyyIntoModel.self) { result in
            JQFXHHUD.jqfxhHttidden()
            switch result {
            case.success(let infoModel):

                if let item = infoModel.products.first {
                    if item.protocolList.count > 0 {
                        //协议弹窗
                        let protocolView = JQFXHProtosggView(frame: CGRectMake(0, 0, jqfxhScreenWidth, self.view.frame.size.height), list: item.protocolList, jqfxhVc: self)
                        protocolView.jqfxhProtocolhhNextBlock = {[weak self] in
                            self?.jqfxhProductaaApply(productIds: infoModel.productIds)
                        }
                        self.view.addSubview(protocolView)
                    } else {
                        self.jqfxhToSuccessrrVC()
                    }
                } else {
                    self.jqfxhToSuccessrrVC()

                }
                
            case .failure(let error):
                print(error)
            }
        }
    }
    
    func jqfxhProductaaApply(productIds:[Int]) -> Void {
        let provider = JQFXHNetworkManager.shared.shengrProvider
        JQFXHNetworkManager.shared.jqfxhRequest(provider: provider, target: .jqfxhProductaaApply(productIds: productIds)) { result in
            JQFXHHUD.jqfxhHttidden()
            switch result {
            case.success(_):
                self.jqfxhToSuccessrrVC()
            case .failure(let error):
                print(error)
            }
        }
    }
    
    func jqfxhToSuccessrrVC() -> Void {
        let successvc = JQFXHLoanSuccessxxController.init()
        self.navigationController?.pushViewController(successvc, animated: true)
    }
    
    
    
     private func jqfxhSetrrupUI() {
         self.view.addSubview(jqfxhSubmitssButton)
         jqfxhSubmitssButton.snp.makeConstraints { make in
             make.left.equalTo(self.view).offset(28)
             make.right.equalTo(self.view).offset(-28)
             make.bottom.equalTo(self.view).offset(-UIApplication.shared.jqfxhSafeAreaInsets.bottom-60)
             make.height.equalTo(42)
         }
         
         self.view.addSubview(jqfxhMoneyCompanyuuLabel)
         jqfxhMoneyCompanyuuLabel.snp.makeConstraints { make in
             make.centerX.equalTo(self.view)
             make.top.equalTo(jqfxhSubmitssButton.snp.bottom).offset(15)
         }
         
         self.view.addSubview(jqfxhCollectionvvView)
         jqfxhCollectionvvView.snp.makeConstraints { make in
             make.left.equalTo(16)
             make.right.equalTo(-16)
             make.top.equalTo(16)
             make.bottom.equalTo(jqfxhSubmitssButton.snp.top).offset(-16)
         }
    }
    
   
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.jqfxhListoos[section].list.count
    }
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        self.jqfxhListoos.count
    }
    
    
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionHeader {
            
            let head = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: JQFXHLoanSectionyyHeaderId, for: indexPath) as! JQFXHLoanSectionyyHeader
            head.updateWithSectionModel(model: self.jqfxhListoos[indexPath.section])
            return head
           
            
        }else{
            if JQFXHNetworkManager.shared.partnerId == 3 && indexPath.section == self.jqfxhListoos.count-1 {
                let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: JQFXHLoanSectioneeFooterId, for: indexPath) as! JQFXHLoanSectioneeFooter
                footer.textChangeBlock = {[weak self] type, text in
                    if type == 1 {
                        self?.jqfxhParappDic["loanAmount"] = text
                    }else {
                        self?.jqfxhParappDic["revenue"] = text
                    }
                }
                return footer
            }
            let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "foot", for: indexPath)
            return footerView
        }
    }
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: jqfxhScreenWidth-36-32, height:45)
        
    }
    
    
    
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JQFXHLoanItemwwCellId, for: indexPath) as! JQFXHLoanItemwwCell
        cell.jqfxhUpdateWithItemxxModel(model: self.jqfxhListoos[indexPath.section].list[indexPath.item])
        return cell
        
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        
        if section == self.jqfxhListoos.count-1 {
            if JQFXHNetworkManager.shared.partnerId == 3 {
                return CGSize(width: jqfxhScreenWidth, height: 100)
            }
            return CGSize(width: jqfxhScreenWidth, height: 16)

        }
        return CGSize(width: jqfxhScreenWidth, height: CGFLOAT_MIN)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var sectionModel = self.jqfxhListoos[indexPath.section]
        for index in 0..<sectionModel.list.count{
            var itemModel = sectionModel.list[index]
            if index == indexPath.row {
                itemModel.isSlected = true
                jqfxhParappDic[sectionModel.key] = itemModel.itemId
            }else {
                itemModel.isSlected = false
            }
            sectionModel.list[index] = itemModel
        }
        self.jqfxhListoos[indexPath.section] = sectionModel
        self.jqfxhCollectionvvView.reloadData()
    }
    
    
    lazy var jqfxhSubmitssButton: UIButton = {
        let jqfxhSubmitssButton = UIButton(type: .custom)
        jqfxhSubmitssButton.setTitle("提交申请", for: .normal)
        jqfxhSubmitssButton.backgroundColor = UIColor.jqfxhThemexxRed
        jqfxhSubmitssButton.setTitleColor(.white, for: .normal)
        jqfxhSubmitssButton.layer.cornerRadius = 8
        jqfxhSubmitssButton.addTarget(self, action: #selector(jqfxhUploadttLoan), for: .touchUpInside)
        return jqfxhSubmitssButton
    }()
    
  
    private lazy var jqfxhLayoutaa: UICollectionViewFlowLayout = {
        let jqfxhLayoutaa = UICollectionViewFlowLayout()
        jqfxhLayoutaa.minimumInteritemSpacing = 12
        jqfxhLayoutaa.scrollDirection = .vertical
        jqfxhLayoutaa.minimumLineSpacing = 12
        jqfxhLayoutaa.itemSize = CGSize(width: (jqfxhScreenWidth-56-32)/3, height: 26)
        jqfxhLayoutaa.sectionInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
        return jqfxhLayoutaa
    }()
    
    
    public lazy var jqfxhCollectionvvView: UICollectionView = {
        
        let jqfxhCollectionvvView = UICollectionView(frame: .zero, collectionViewLayout: self.jqfxhLayoutaa)
                        
        jqfxhCollectionvvView.register(JQFXHLoanSectionyyHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: JQFXHLoanSectionyyHeaderId)
        jqfxhCollectionvvView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "foot")
        jqfxhCollectionvvView.register(JQFXHLoanSectioneeFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: JQFXHLoanSectioneeFooterId)
        jqfxhCollectionvvView.register(JQFXHLoanItemwwCell.self, forCellWithReuseIdentifier: JQFXHLoanItemwwCellId)
        
        jqfxhCollectionvvView.backgroundColor = UIColor.white
        jqfxhCollectionvvView.showsVerticalScrollIndicator = false
        jqfxhCollectionvvView.showsHorizontalScrollIndicator = false
        jqfxhCollectionvvView.keyboardDismissMode = .onDrag  // 在拖动时隐藏键盘

        jqfxhCollectionvvView.layer.cornerRadius = 12
        jqfxhCollectionvvView.layer.masksToBounds = true

        if #available(iOS 11.0, *) {
            jqfxhCollectionvvView.contentInsetAdjustmentBehavior = .never
        }
        jqfxhCollectionvvView.alwaysBounceVertical = true
        jqfxhCollectionvvView.delegate = self
        jqfxhCollectionvvView.dataSource = self
        return jqfxhCollectionvvView
    }()
    
    lazy var jqfxhMoneyCompanyuuLabel : UILabel = {
        let jqfxhMoneyCompanyuuLabel = UILabel()
        jqfxhMoneyCompanyuuLabel.text = JQFXHCompanyMessage.jqfxhZhongMoneyCompanyName
        jqfxhMoneyCompanyuuLabel.font = UIFont.jqfxhMedium13
        jqfxhMoneyCompanyuuLabel.textColor = UIColor.jqfxhTextLightaaGray
        return jqfxhMoneyCompanyuuLabel
    }()
    
    
    
}

public let JQFXHLoanItemwwCellId = "JQFXHLoanItemwwCell"


class JQFXHLoanItemwwCell: UICollectionViewCell {
    
    lazy var jqfxhTitlezzLabel : UILabel = {
        let jqfxhTitlezzLabel = UILabel()
        jqfxhTitlezzLabel.font = UIFont.jqfxhRegular14
        jqfxhTitlezzLabel.textColor = UIColor.jqfxhTextLightaaGray
        jqfxhTitlezzLabel.textAlignment = .center
        return jqfxhTitlezzLabel
    }()
    
    
    lazy var jqfxhBackImageyyView : UIImageView = {
        let imageView = UIImageView()
        imageView.backgroundColor = UIColor.jqfxhSmallViewBgbbGray
        imageView.layer.cornerRadius = 4
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    public override init(frame: CGRect) {
    
        super.init(frame: frame)
        self.addSubview(jqfxhBackImageyyView)
        self.contentView.addSubview(jqfxhBackImageyyView)
        jqfxhBackImageyyView.snp.makeConstraints { make in
            make.edges.equalTo(self.contentView)
        }
        self.contentView.addSubview(jqfxhTitlezzLabel)
        jqfxhTitlezzLabel.snp.makeConstraints { make in
            make.edges.equalTo(self.contentView)
        }
    }
    
    func jqfxhUpdateWithItemxxModel(model:JQFXHSelectedItemttModel) -> Void {
        if model.isSlected {
            self.jqfxhBackImageyyView.backgroundColor = UIColor.jqfxhEasyRedvvBg
            jqfxhBackImageyyView.layer.masksToBounds = true
            jqfxhTitlezzLabel.textColor = UIColor.jqfxhThemexxRed
            
        }else {
            self.jqfxhBackImageyyView.backgroundColor = UIColor.jqfxhSmallViewBgbbGray
            jqfxhBackImageyyView.layer.masksToBounds = false
            jqfxhTitlezzLabel.textColor = UIColor.black
        }
        self.jqfxhTitlezzLabel.text = model.itemName
    }
    
    
    
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


public let JQFXHLoanSectionyyHeaderId = "JQFXHLoanSectionyyHeader"

class JQFXHLoanSectionyyHeader: UICollectionReusableView {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        self.addSubview(jqfxhTitlezzLabel)
        jqfxhTitlezzLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(15)
        }
    }
    
   
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    func updateWithSectionModel(model:JQFXHLoanListuuItemModel) -> Void {
        self.jqfxhTitlezzLabel.text = model.name
    }
    
    
    lazy var jqfxhTitlezzLabel : UILabel = {
        let jqfxhTitlezzLabel = UILabel()
        jqfxhTitlezzLabel.font = UIFont.jqfxhRegular14
        jqfxhTitlezzLabel.textColor = UIColor.black
        return jqfxhTitlezzLabel
    }()
    
    
}

extension JQFXHLoanSectioneeFooter : UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        self.textChangeBlock?(textField.tag, textField.text ?? "")
        
        return true

    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.textChangeBlock?(textField.tag, textField.text ?? "")
    }
}



typealias TextChangeBlock = (Int, String) -> Void

public let JQFXHLoanSectioneeFooterId = "JQFXHLoanSectioneeFooter"

class JQFXHLoanSectioneeFooter: UICollectionReusableView {
    
    var textChangeBlock : TextChangeBlock?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        self.addSubview(jqfxhEduTitleaaLabel)
        jqfxhEduTitleaaLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(15)
            make.height.equalTo(40)
        }
        
        self.addSubview(jqfxhEdubbTf)
        jqfxhEdubbTf.snp.makeConstraints { make in
            make.centerY.equalTo(jqfxhEduTitleaaLabel)
            make.left.equalTo(jqfxhEduTitleaaLabel.snp.right).offset(20)
        }
        
        self.addSubview(jqfxhIncomeccTitleLabel)
        jqfxhIncomeccTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhEduTitleaaLabel)
            make.top.equalTo(jqfxhEduTitleaaLabel.snp.bottom)
            make.height.equalTo(40)
        }
        
        self.addSubview(jqfxhInddcomeTf)
        jqfxhInddcomeTf.snp.makeConstraints { make in
            make.centerY.equalTo(jqfxhIncomeccTitleLabel)
            make.left.equalTo(jqfxhIncomeccTitleLabel.snp.right).offset(20)
        }
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func jqfxhDoneTapped() {
        self.endEditing(true) // 收起键盘
    }
    
    
    lazy var jqfxhEdubbTf : UITextField = {
        let jqfxhEdubbTf = UITextField()
        jqfxhEdubbTf.font = UIFont.jqfxhRegular14
        jqfxhEdubbTf.keyboardType = .numberPad
        jqfxhEdubbTf.placeholder = "请输入贷款额度"
        jqfxhEdubbTf.delegate = self
        jqfxhEdubbTf.jqfxhAddDoneButtoneeOnKeyboard(target: self, action: #selector(jqfxhDoneTapped))
        jqfxhEdubbTf.tag = 1
        return jqfxhEdubbTf
    }()
    

    lazy var jqfxhEduTitleaaLabel : UILabel = {
        let jqfxhTitlezzLabel = UILabel()
        jqfxhTitlezzLabel.font = UIFont.jqfxhRegular18
        jqfxhTitlezzLabel.textColor = UIColor.black
        jqfxhTitlezzLabel.text = "贷款额度"
        return jqfxhTitlezzLabel
    }()
    
    lazy var jqfxhIncomeccTitleLabel : UILabel = {
        let jqfxhIncomeccTitleLabel = UILabel()
        jqfxhIncomeccTitleLabel.font = UIFont.jqfxhRegular18
        jqfxhIncomeccTitleLabel.textColor = UIColor.black
        jqfxhIncomeccTitleLabel.text = "月收入"
        return jqfxhIncomeccTitleLabel
    }()
    
    
    lazy var jqfxhInddcomeTf : UITextField = {
        let jqfxhInddcomeTf = UITextField()
        jqfxhInddcomeTf.font = UIFont.jqfxhRegular14
        jqfxhInddcomeTf.keyboardType = .numberPad
        jqfxhInddcomeTf.placeholder = "请输入月收入"
        jqfxhInddcomeTf.tag = 2

        jqfxhInddcomeTf.delegate = self
        jqfxhInddcomeTf.jqfxhAddDoneButtoneeOnKeyboard(target: self, action: #selector(jqfxhDoneTapped))
        return jqfxhInddcomeTf
    }()
    
    
    
   
    
    
}



